<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Task;
use App\Models\TaskReply;
use App\Models\User;
use App\Models\TaskProcess;
use App\Models\TaskComment;
use App\Models\TaskService;
use App\Models\Service;
use App\Models\Client;
use App\Models\ClientUser;
use App\Models\ClientCar;
use App\Repos\TaskRepo;
use App\Repos\DepartRepo;
use App\Models\MaintainType;
use App\Models\ServiceType;
use Session;
use DB,Log;
use App\Services\Wechat;
use App\Services\Msgtpl;
use Image;

class TaskController extends Controller
{
    public function index( Request $request)
    {
        $wx_user =  session('wechat.oauth_user.default');
        //dd($wx_user);
        $where   = $param = [];
        $client_ids  = ClientUser::where(['openid'=>$wx_user->id])->pluck('client_id');
        
        $query   = Task::whereIn('client_id',$client_ids);
        
        if($request->keyword) {
            $car_ids = ClientCar::where('car_num','like','%'.$request->keyword.'%')->pluck('id');
            $query->whereIn('car_id',$car_ids);
            $param['keyword'] = trim($request->keyword);
        }

        $list = $query->with('car')->orderBy('created_at','desc')
                    ->paginate(8);
        
        $servicetypes = ServiceType::get();           
                          
        return view('4s.task-list',compact('list','param','servicetypes'));
        
    }

    public function create()
    {     

        $wx_user    = session('wechat.oauth_user.default');
        $openid     = $wx_user->id;
        $worker     = User::where('openid',$openid)->first();
        if(!$worker) {
            $rs['msg']    = '没有权限';
            $rs['status'] = 'danger';
            return redirect('/user/task')->with('rs',$rs);
        }
        $expert = [];
        $types = MaintainType::where('pid',4)->get();
       
        return view('4s.task-add',compact('data','types'));
    }   

   

    public function save(Request $request)
    {
        
    	$rs['status'] = 'danger';   
        $wx_user    = session('wechat.oauth_user.default');
        $openid     = $wx_user->id;
        $worker     = User::where('openid',$openid)->first();   
        $data         = $request->except(['_token']); 
        $car = ClientCar::where(['car_num'=>$data['car_num']])->first();
        if(empty($car))
        {
            $rs['msg'] = '车牌号码不存在';
            return back()->with('rs',$rs)->withInput();
        }

        // 根据 car_num 获取 car_id 和 client_id;
        DB::beginTransaction();
        try{
           
           $code = date('Ymdhis').str_random(3);
          
           
           $data['car_id']    = $car->id;
           $data['client_id'] = $car->client_id;         
           $data['status']    = 50 ;
           $data['code']      = $code;
           $data['worker_id'] = $worker->id;
           $flag = Task::create($data);

            
            if(!$flag) {
                DB::rollBack();
                return back()->with($rs);
            } 
            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['msg'] = $e->getMessage();
            return back()->withInput()->with('rs',$rs);
        }
    	
        
        $rs['status'] = 'success';
        $rs['msg']    = '工单提交成功';

        try {
           // 推送消息
            $data = $flag->toArray();
            TaskRepo::newTaskPush($data);
        } catch (\Exception $e) {
            $rs['msg']    = $e->getMessage();
            return back()->withInput()->with('rs',$rs);
        }
        
        //return response()->json($rs);
       return redirect('user/task')->with('rs',$rs);    
       // return back()->withInput()->with('rs',$rs);

    }

  


    public function show($id)
    {
        $data = Task::withTrashed()->find($id);
       
       
        $wechat_user = session('wechat.oauth_user.default');
        $openid      = $wechat_user->id;
        $worker      = User::where('openid',$openid)->first();
       
       //dd($wechat_user,$openid,$worker);
        return view('4s.task-show',compact('data','worker'));
    }   

    public function process(Request $request)
    {
        
        $rs['status'] = 'danger';
        $rs['msg']    = '操作成功';  
        $data = $request->except(['_token']);     
        $flag = TaskRepo::dispatch($data);
        if($flag == true) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        } 
        return back()->with('rs',$rs);
        
    }

    // 报价信息
    public function processPrice(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);
        $wechat_user =  session('wechat.oauth_user.default');
        $data['worker_openid'] = $wechat_user->id;
        $data['status'] = 0;      

        $flag = TaskService::create($data);
        $task = Task::find($data['task_id']);
        $task->status = 75;
        $task->money = $data['service_price'];
        $task->save();
        
        $process = array_only($data,['task_id','worker_openid','status']);
        $user = User::where('openid',$wechat_user->id)->first();
        $process['worker_id']      = $user->id;
        $process['creater_openid'] = $wechat_user->id;
        $process['remark'] = '报价：'.$data['service_name'].','.$data['service_price'];
        $process['money'] = $data['service_price'];
        $process['status'] = 75;
        TaskProcess::create($process);
        $msg = $data;
        $msg['first'] = '工单报价';
        $msg['openid']        =  $task->openid;
        $msg['customer_name'] = $task->customer_name;
     
        $msg['remark'] = $process['remark'];
        $msg['url']    = config('app.url').'/user/task/price-detail/'.$flag->id;
        Wechat::sendMsgTpl('price_to_user',$msg);  // 推送报价给客户

        if($flag) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        }
        return back()->with('rs',$rs);
    }

    /**
     * 工单报价详情
     */
    public function priceDetail($id)
    {
        $price = TaskService::find($id);
        $task = Task::find($price->task_id);
        return view('hrs.task.price',compact('price','task'));
    }

    /**
     * 用户确认工单费用
     */
    public function priceConfirmed(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg'] = '操作失败';
        $taskService = TaskService::find($request->task_service_id);
        $taskService->status = $request->status;
        $flag = $taskService->save();

        if($request->status == -1) {
            Task::where('id',$taskService->task_id)->update(['status'=>'-1']);
            $where['task_id'] = $taskService->task_id;
            $where['worker_openid'] = $taskService->worker_openid;
            $process = TaskProcess::where($where)->first()->toArray();
            $process['status'] = '-1';
            $process['remark'] = '用户拒绝付款';
            $process['creater_openid'] = $taskService->task_openid;
            TaskProcess::create($process);
        }

        if($flag == true) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return redirect('user/task/show/'.$taskService->task_id)->with('rs',$rs);
        } 
        return redirect('user/task/show/'.$taskService->task_id)->with('rs',$rs);
    }

    /**
     * 完工
     */
    public function complete(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败'; 

           
        $taskProcess = TaskProcess::where('task_id',$request->task_id)->first();
        if($taskProcess) {
            $taskProcess = $taskProcess->toArray();
            $taskProcess = array_except($taskProcess,['created_at','updated_at']);
                   
            $taskProcess['status'] = 100; 
            $taskProcess['remark'] = $request->remark; 
                       
            $flag = TaskProcess::create($taskProcess);
        }       

        $task   = Task::find($request->task_id);
        $task->status = 100;
        $task->completed_at     = date('Y-m-d H:i:s');
        $task->completed_remark = $request->remark;
        $flag   = $task->save();        
        

        // 推送消息
        if( object_get($task,'client.openid') ) {
            $msg      = $task->toArray();
            $msg['first']  = '车辆完工通知';
            $msg['car_num'] = $task->car_num?$task->car_num:$task->car->car_num;
            $msg['openid'] = object_get($task,'client.openid');
            $msg['url']    = config('app.url').'/user/task/comment?task_id='.$task->id;

            Wechat::sendMsgTpl('complete_to_client&driver',$msg);  // 先推送给客户    
        }
        
        
        

        if($flag == true) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        } 
        return back()->with('rs',$rs);
        
    }



    public function comment(Request $request)
    {
        $task_id = (int)$request->task_id;
        $data = Task::withTrashed()->find($task_id);   
        $comments = TaskComment::where(['task_id'=>$task_id])
                                ->get();  
                               //dd($comments); 
        return view('4s.task-comment',compact('data','comments'));
    }

    public function commentSave(Request $request)
    {
       
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);       
        $task = Task::find($request->task_id);
        $task->status = 200;
        $task->save();
        $flag = TaskComment::create($data);
        
        if($flag) {
            // 推送消息
            $msg      = $task->toArray();
          
            $msg['car_num']  = $task->car_num?$task->car_num:$task->car->car_num;
            $msg['maintian'] = object_get($data,'maintian.name');
            $msg['openid']   = object_get($task,'client.openid');
            $msg['url']      = config('app.url').'/user/task/comment?task_id='.$task->id;

            Wechat::sendMsgTpl('comment',$msg);   

            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        } 

        
        return back()->with('rs',$rs);
    }

     /**
     * 退单
     */
    public function refund(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg'] = '操作失败';
        $data = $request->all();
       // dd($data);
        $wechat_user =  session('wechat.oauth_user.default'); 
        $user = User::where('openid',$wechat_user->id)->first();
        $data['username'] = $user->username."($user->truenmae)";
        $flag = TaskRepo::refund($data);       
        if($flag['status']==true) {
            $rs['status'] = 'success';
            $rs['msg']    = '操作成功';
        }

        return back()->with('rs',$rs);
    }


}
